﻿using Microsoft.AspNetCore.Diagnostics;
using SimpleTicketBooking.Models.Response;

namespace SimpleTicketBooking.Middlewares
{
    /// <summary>
    /// handle uncaughed errors
    /// </summary>
    public static class UseGlobalExceptionMiddlerware
    {
        /// <summary>
        /// logging logic
        /// </summary>
        /// <param name="app"></param>
        /// <returns></returns>
        public static IApplicationBuilder UseException(this IApplicationBuilder app)
        {
            return app.UseExceptionHandler(configure =>
            {
                configure.Run(async context =>
                {
                    var exceptionHandlerPathFeature = context.Features.Get<IExceptionHandlerPathFeature>();
                    var ex = exceptionHandlerPathFeature?.Error;
                    if (ex != null)
                    {
                        var _logger = context.RequestServices.GetService<ILogger<IExceptionHandlerPathFeature>>();
                        var rspResult = ResponseResult<object>.Failed(ex.Message);
                        _logger?.LogError(ex, message: ex.Message);
                        context.Response.StatusCode = StatusCodes.Status500InternalServerError;
                        context.Response.ContentType = "application/json;charset=utf-8";
                        await context.Response.WriteAsync(rspResult.SerializeObject());
                    }
                });
            });
        }
    }
}
